package cn.itcast.oa.view.action;

import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.oa.base.BaseAction;
import cn.itcast.oa.domain.Department;
import cn.itcast.oa.util.DepartmentUtil;

import com.opensymphony.xwork2.ActionContext;

@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class DepartmentAction extends BaseAction<Department>{

	
	
//	@Resource
//	private DepartmentService departmentService ;
//	private Department model = new Department() ;
//	
//	public Department getModel() {
//		return model;
//	}
	
	private Long parentId ;
	
	
	/**查询所有*/
	public String list() throws Exception {
		List<Department> departmentList = null ;
		if (parentId == null ) {
			// 查询顶级部门列表
			departmentList = departmentService.findTopList() ;
		}else{
			// 查询子部门列表
			departmentList = departmentService.findChildren(parentId) ;
			//得到上级部门的parent对象
			Department parent = departmentService.getById(parentId);
			ActionContext.getContext().put("parent", parent);
		}
		ActionContext.getContext().put("departmentlist", departmentList);
		return "list";
	}
	/**删除数据*/
	public String delete() throws Exception {
		departmentService.delete(model.getId());
		return "toList";
	}
	/**修改页面*/
	public String editUI() throws Exception {
		
		List<Department> topList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtil.getAllDepartments(topList);
		ActionContext.getContext().put("departmentlist", departmentList);
		
		//准备回显的数据
		Department department = departmentService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(department);
		
		if(department.getParent() != null){
			parentId = department.getParent().getId();
		}
		return "saveUI";
	}
	/**修改操作*/
	public String edit() throws Exception {
		Department department = departmentService.getById(model.getId());
		department.setName(model.getName());
		department.setDescription(model.getDescription());
		department.setParent(departmentService.getById(parentId));//设置属性的上级部门
		departmentService.update(department);
		return "toList";
	}
	/**增加操作*/
	public String add() throws Exception {
		Department parent = departmentService.getById(parentId);
		model.setParent(parent);
		departmentService.save(model);
		return "toList";
	}
	/**增加页面*/
	public String addUI() throws Exception {
//		List<Department> departmentlist = departmentService.findAll();
		List<Department> topList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtil.getAllDepartments(topList);
		ActionContext.getContext().put("departmentlist", departmentList);
		
		return "saveUI";
	}
	
	//-------------------------
	public Long getParentId() {
		return parentId;
	}
	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}
	
	
	

}
